const {src, dest, watch, series, symlink} = require('gulp');
const babel = require('gulp-babel');
const uglify = require('gulp-uglify');
const rename = require('gulp-rename');
const gulpif = require('gulp-if');
const del = require('del');
const vinylPaths = require('vinyl-paths');
const sass = require('gulp-sass');
const postcss = require('gulp-postcss');
const torpx = require('postcss-px2rpx');
const autoprefix = require('autoprefixer');
const sourcemaps = require('gulp-sourcemaps');
const cssnano = require('cssnano');
const base64 = require('postcss-base64');
const imagemin = require('gulp-imagemin');
const htmlmin = require('gulp-htmlmin');
const env = require('./bin/env');
const isProd = env.prod == process.env.NODE_ENV;
const multiplier = env.DefaultWidth/env.UIMaxWidth;
sass.compiler = require('node-sass');


// console.log(process.env.NODE_ENV)

function clean(){
    return del(['./dist'])
}

function handelError(err){
    console.log(err);
}

function imageTask(){
    return src('image/**/*')
    .pipe(imagemin())
    .pipe(dest('./dist/image'))
}
function htmlTask(){
    return src('src/**/*.html')
    .pipe(htmlmin({
        removeComments: true,               // 清除HTML注释
        collapseWhitespace: true,           // 压缩空格
        collapseBooleanAttributes: true,    // 省略布尔属性的值 <input checked="true"/> => <input checked>
        removeEmptyAttributes: true,        // 删除所有空格作属性值 <input id=""> => <input>
        removeScriptTypeAttributes: true,   // 删除<script>的type="text/javascript"
        removeStyleLinkTypeAttributes: true,// 删除<style>和<link>的type="text/css"
        minifyJS: true,                     // 压缩页面JS
        minifyCSS: true                     // 压缩页面CSS
    }))
    .pipe(dest('dist'))
}

function sassTask(){
    return src('src/**/*.{scss,css}')
    .pipe(sass().on('error', handelError))
    .pipe(postcss([/*torpx({
        times:multiplier
    }), */autoprefix(), cssnano(),base64({
        debug: true,
        extensions: ['.svg', '.ttf', '.woff', '.woff2']
    })]))
    .pipe(gulpif(!isProd, sourcemaps.init()))
    .pipe(rename({
        extname: '.min.css'
    }))
    .pipe(gulpif(!isProd, sourcemaps.write('maps')))
    .pipe(dest('dist/css/'))
}


function moveFile(){
    // console.log(1);
    return src('./src/**/*.js')
    .pipe(src('./another/*'))
    .pipe(babel())
    .pipe(gulpif(isProd, rename({
        extname: '.min.js'
    })))
    .pipe(gulpif(isProd, uglify()))
    .pipe(dest('dist/'))
    // .pipe(vinylPaths(del))
}
function watchTask(){
    return watch('./src/*', {
        ignoreInitial: false
    }, series(del, moveFile));
}

function link() {
    return src('src/*.js')
    .pipe(symlink('another/'));
}

function build(){
    return series([clean, moveFile, sassTask, imageTask, htmlTask])
}

exports.link = link
exports.sassTask = sassTask;
exports.watchTask = watchTask;
exports.del = clean;
exports.default = build();